from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import Future

class AsynTask(object):
    """docstring for AsynTask
        must implement callback, do

        do (sample):
        def do(self,url):
            try:
                response = ur.urlopen(url)        
            except Exception  as e:
                print(e)
            except Future.exception(timeout=self.timeout):
                print("time out :",self.timeout)
            finally:
                return response 

        callback (sample):
        def callback(self,future):
            result = future.result()
            if future in  HTTP.temp_future:
                arg = HTTP.temp_future[future]
            with open(arg[-1]+".log","w") as fp:
                print(result,file=fp

    """
    executor = None
    temp_future = None
    def __init__(self,max_process=5,timeout=5):

        if AsynTask.executor != None :pass
        else:
            print(" ---- init executor ----")
            self.timeout = timeout
            AsynTask.executor = ProcessPoolExecutor(max_workers=max_process)
            AsynTask.temp_future = {}
    
    def do_background(self,args,callback=None):
        """
        must give a callback for some dealing just like deal with UI.
        @args must () or []
        @callback should implement or pass .

        """
        con = None
        if isinstance(args,list):
            args.append(deal)
            con = AsynTask.executor.submit(self.do,*args)
        else:
            con = AsynTask.executor.submit(self.do,args)
        
        # must give a callback for some dealing just like deal with UI
        if callback == None:  
            con.add_done_callback(self.callback)
        else:
            con.add_done_callback(callback)

        AsynTask.temp_future[con] = args

    def get_args(self,future):
        r = AsynTask.temp_future[future]
        del AsynTask.temp_future[future]
        return r

    def clear(self):
        AsynTask.executor = None


    def callback(self,future):
        """
        this is must implement
        """
        # result = future.result()
        # args = self.get_args(future)
        # print("args : ",args,"\nresult: ",result )

    def do(self):
        """
         this is must implement
        """
        pass

